package org.jeecg.modules.yw.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.InetAddress;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import lombok.extern.slf4j.Slf4j;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;

/**
 * 通用工具类
 * @author cs
 *
 */
@Slf4j
public class CommonUtils {
    public static String PWD="pass123";
    public static String ADMIN="f6817f48af4fb3af11b9e8bf182f618b";
    public static String NQZG="nqzg";
//    @Resource
//    private AliyunConfig aliyunConfig;

	public static ExpiringMap<String,String> expireMap = ExpiringMap.builder()
	        .expiration(300, TimeUnit.SECONDS)
	        .expirationPolicy(ExpirationPolicy.ACCESSED)
	        .variableExpiration()
	        .build();

    public static Double scientificToNumber(String number) {
        BigDecimal bd = new BigDecimal(number);
        String decimalString = bd.toPlainString();
        return Double.parseDouble(decimalString);
    }

	/**
	 * 获取id
	 * @return
	 */
	public static String getID() {
		 String id = UUID.randomUUID().toString().replaceAll("-", "");
		 return id;
	}


    private static String calculateMD5(String originalString) {
        try {
            // 创建MD5加密实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 执行加密操作
            byte[] messageDigest = md.digest(originalString.getBytes());

            // 将得到的散列值转换为十六进制
            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) {
                sb.append(String.format("%02x", b));
            }

            // 返回MD5散列值
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密算法不可用", e);
        }
    }
    /*
    * 检查手机号格式
    * */
    public static int isValidPhoneNumber(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        boolean b = phoneNumber.matches(regex);
        if (b){
            return 1;
        }else {
            return 0;
        }
    }

    /**
     * 返回6位随机数
     * @return
     */
    public static String get6bitString() {
    	 Random random = new Random();
         int randomNumber = random.nextInt(900000) + 100000;
         System.out.println(randomNumber);
         return String.valueOf(randomNumber);
    }

    public static String getServerIpAndPort(HttpServletRequest request) throws Exception {
        InetAddress localhost = InetAddress.getLocalHost();
        // 获取服务器IP地址
        String serverIp = request.getRequestURI();
        // 获取服务器端口号
        int serverPort = request.getServerPort();
        // 拼接结果
        return serverIp+":"+serverPort;
    }
    public static String sendSMS(String phone, String idntCode) throws  com.aliyuncs.exceptions.ClientException {
        //将外部生成的四位数验证码塞入赋值
        String i = idntCode;
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";                                          //短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";                              //短信API产品域名（接口地址固定，无需修改）
        //替换成你的AK

        final String accessKeyId = "LTAI5tSTPKGPjtqBhSo9M67B";                              //你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "Do5oWqqxA1vNNngs0ORpNsfPc3TAu8";            //你的accessKeySecret，参考本文档步骤2
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,
        // 验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000"
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("黑龙江涵煦熙建筑工程");
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode("SMS_314665373");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        request.setTemplateParam("{\"code\":\""+ i +"\"}");
        //请求失败抛出失败的异常
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        //请求成功打印OK
        if(sendSmsResponse.getCode() !=null && sendSmsResponse.getCode().equals("OK")){
            return "OK";
        }
        return "";
    }
    
    /**
     * 价格添加方法
     * @param orginalPrice
     * @param addPrice
     * @return
     */
    public static String addPrice(String orginalPrice, String addPrice) {
    	if (StringUtils.isBlank(orginalPrice)) {
    		return "0";
    	}
    	String addAfter = new BigDecimal(orginalPrice).add(new BigDecimal(addPrice)).toString();
    	return addAfter;
    }
    
    /**
     * 价格乘法
     * @param orginalPrice
     * @param addPrice
     * @return
     */
    public static String MultiPrice(String orginalPrice, Integer num) {
    	if (StringUtils.isBlank(orginalPrice)) {
    		return "0";
    	}
    	String addAfter = new BigDecimal(orginalPrice).multiply(new BigDecimal(num)).toString();
    	return addAfter;
    }
    
    public static String Keep2Bits(String price) {
    	if (StringUtils.isNotBlank(price)) {
    		return new BigDecimal(price).setScale(2, RoundingMode.HALF_UP).toString();
    	}
    	return "0.00";
    }
    
    public static String getToolName(String toolType){
        HashMap<String,String> map = new HashMap<>();
        map.put("1","发泡");
        map.put("2","拉爆螺丝");
        map.put("3","自切螺丝");
        map.put("4","瓦斯钉");
        map.put("5","工具");
        map.put("6","外墙胶");
        map.put("7","内墙胶");
        map.put("8","外玻璃胶");
        map.put("9","内玻璃胶");
        return map.get(toolType);
    }
	public static void main(String args[]) {
		System.out.println(getID());
        String originalString = "Hello, World!";
        System.out.println("Original String: " + originalString);
        System.out.println("MD5 Hash: " + calculateMD5(originalString));
        String d= scientificToNumber("1.2345e+5").toString();
        System.out.println(d);
        System.out.println(get6bitString());
	}

}
